const path = require("path");
const os = require("os");
const fs = require("fs");
const {
  findVulnerableDependencies,
} = require("../../lib/npm/vulnerability-auditor");
const helpers = require("./helpers");

describe("findVulnerableDependencies", () => {
  let tempDir;
  beforeEach(() => {
    tempDir = fs.mkdtempSync(os.tmpdir() + path.sep);
  });
  afterEach(() => fs.rm(tempDir, { recursive: true }, () => {}));

  it("finds vulnerable dependencies", async () => {
    helpers.copyDependencies("vulnerability-auditor/simple", tempDir);

    const advisories = [{
      dependency_name: "@dependabot-fixtures/npm-parent-dependency",
      affected_versions: [
        ">= 0, < 2.0.2",
      ]
    }];
    const actual = await findVulnerableDependencies(tempDir, advisories);
    const expected = {
      dependency_name: "@dependabot-fixtures/npm-parent-dependency",
      fix_updates: [
        {
          dependency_name: "@dependabot-fixtures/npm-parent-dependency",
          current_version: "2.0.0",
          top_level_ancestors: [],
          target_version: "2.0.2"
        },
      ],
      top_level_ancestors: [
        "@dependabot-fixtures/npm-parent-dependency"
      ],
      current_version: "2.0.0",
      fix_available: true,
      target_version: "2.0.2"
    };
    expect(actual).toEqual(expected);
  });

  it("finds vulnerable dependencies when multiple versions of the same package are affected", async () => {
    helpers.copyDependencies("vulnerability-auditor/update-needed-across-two-versions", tempDir);

    const advisories = [{
      dependency_name: "@msgpack/msgpack",
      affected_versions: [
        ">= 2.0.0, < 2.8.0",
        ">= 3.0.0, < 3.1.2"
      ]
    }];
    const actual = await findVulnerableDependencies(tempDir, advisories);
    const expected = {
      dependency_name: "@msgpack/msgpack",
      fix_updates: [
         {
          dependency_name: "@msgpack/msgpack",
          current_version: "2.7.2",
          top_level_ancestors: [],
          target_version: "2.8.0"
        },
        {
        dependency_name: "@msgpack/msgpack",
        current_version: "3.0.0",
        top_level_ancestors: [
            "wireql-client"
          ],
          target_version: "3.1.2"
        }
      ],
      top_level_ancestors: [
        "@msgpack/msgpack",
        "wireql-client"
      ],
      current_version: "2.7.2",
      fix_available: true,
      target_version: "2.8.0"
    };
    expect(actual).toEqual(expected);
  });
});
